const user = require('@koa/router')()
const DB = require('../controllers/db')
const tk = require('../utils/token')


user.post('/changepwd', async (ctx, next) => {
  if (ctx.request.body.userName && ctx.request.body.userPwd && ctx.request.body.userNewPwd) {
    const msg = await DB.userChangePassword(ctx.request.body.userName, ctx.request.body.userPwd, ctx.request.body.userNewPwd)
    ctx.body = msg
  } else {
    ctx.body = {
      code: 408,
      msg: `未携带必要参数`
    }
  }
})

user.post('/sendemail', async (ctx, next) => {
  if (ctx.request.body.userName) {
    const msg = await DB.sendEmailtoUser(ctx.request.body.userName)
    ctx.body = msg
  } else {
    ctx.body = {
      code: 408,
      msg: `未携带必要参数`
    }
  }
})

user.post('/detail', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      const msg = await DB.userDetail(ctx.request.body.userName)
      ctx.body = msg
    }
  }
})

user.post('/nickname', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      if (ctx.request.body.userId) {
        const msg = await DB.userChangeNickName(ctx.request.body.userId, ctx.request.body.nickName)
        ctx.body = msg
      } else {
        ctx.body = {
          code: 408,
          msg: `未携带必要参数`
        }
      }
    }
  }
})

user.post('/avatar', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      if (ctx.request.body.userId) {
        const msg = await DB.userChangeAvatar(ctx.request.body.userId, ctx.request.body.avatar)
        ctx.body = msg
      } else {
        ctx.body = {
          code: 408,
          msg: `未携带必要参数`
        }
      }
    }
  }
})

user.post('/sign', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      if (ctx.request.body.userId) {
        const msg = await DB.userChangeSign(ctx.request.body.userId, ctx.request.body.sign)
        ctx.body = msg
      } else {
        ctx.body = {
          code: 408,
          msg: `未携带必要参数`
        }
      }
    }
  }
})



module.exports = user